#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/4 11:01
# @Author  : Andrewq
# @Site    : nope
# @File    : EmployeeInfoModel.py
# @Software: PyCharm
import datetime

from flask import current_app

from .models import DepartmentInfo, EmployeeInfo
from .. import db
from ..utils import commons
from ..utils.response_code import RET


class EmployeeInfoManager(EmployeeInfo):
    @classmethod
    def get_employee_all_data(cls):
        filter_list = []

        try:

            employees = db.session.query(cls).filter(*filter_list)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        if not employees.first():
            return {'code': RET.NODATA, 'message': '没有员工数据'}

        back_data = commons.query_to_dict(employees.all())

        try:
            for data in back_data:
                department = db.session.query(DepartmentInfo).filter(
                    DepartmentInfo.DepartmentID == data.get('DepartmentID'))
                data['DepartmentName'] = commons.query_to_dict(department.first())['DepartmentName']
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        return {'code': RET.OK, 'message': '查询用户信息成功', 'data': back_data}

    @classmethod
    def add_employee_info(cls, **kwargs):
        department_name = kwargs.get('DepartmentName')

        filter_list = []
        filter_list.append(DepartmentInfo.DepartmentName == department_name)

        try:
            department_ID = db.session.query(DepartmentInfo.DepartmentID).filter(*filter_list)

            if not department_ID.first():
                return {'code': RET.NODATA, 'message': '没有部门数据'}

            user_ID = (datetime.datetime.now()).strftime('%Y%m%d%H%M%S')

            User = EmployeeInfo(
                UserID=user_ID,
                UserName=kwargs.get('UserName'),
                DepartmentID=department_ID
            )

            db.session.add(User)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        data = commons.query_to_dict(User)

        return {'code': RET.OK, 'message': '添加数据成功', 'data': data}

    @classmethod
    def delete_employee_info_list(cls, **kwargs):
        data = kwargs.get('data')
        ID_list = []
        try:
            for item in data:
                ID_list.append(item['data']['UserID'])
            for ID in ID_list:
                filter_list = []
                filter_list.append(cls.UserID == ID)

                employee = db.session.query(cls).filter(*filter_list)

                if not employee.first():
                    return {'code': RET.NODATA, 'message': '没有用户数据'}

                employee.delete()
                db.session.commit()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        return {'code': RET.OK, 'message': '成功删除数据', 'data': data}

    @classmethod
    def delete_employee_info(cls, **kwargs):
        filter_list = []

        filter_list.append(cls.UserID == kwargs.get('UserID'))

        try:
            employee = db.session.query(cls).filter(*filter_list)

            if not employee.first():
                return {'code': RET.NODATA, 'message': '没有用户数据'}

            employee.delete()
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        back_data = {
            'UserID': kwargs.get('UserID'),
        }

        return {'code': RET.OK, 'message': '删除用户数据成功', 'data': back_data}

    @classmethod
    def edit_employee_info(cls, **kwargs):
        filter_list = []

        filter_list.append(DepartmentInfo.DepartmentName == kwargs.get('DepartmentName'))

        try:
            Department = db.session.query(DepartmentInfo).filter(*filter_list)

            if not Department.first():
                return {'code': RET.NODATA, 'message': '没有该部门数据'}

            kwargs.update({'DepartmentID': commons.query_to_dict(Department.first())['DepartmentID']})

            filter_list = []
            filter_list.append(cls.UserID == kwargs.get('UserID'))

            Employee = db.session.query(cls).filter(*filter_list)

            if not Employee.first():
                return {'code': RET.NODATA, 'message': '没有用户数据'}

            Employee.update({'UserName': kwargs.get('UserName'), 'DepartmentID': kwargs.get('DepartmentID')})
            db.session.commit()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        return {'code': RET.OK, 'message': '修改信息成功', 'data': kwargs}

    @classmethod
    def get_employee_info_by_tags(cls, **kwargs):
        tag_name = kwargs.get('tag')
        filter_list = []
        if tag_name == '部门名':
            filter_list.append(DepartmentInfo.DepartmentName.contains(kwargs.get('keyword')))
        elif tag_name == '用户ID':
            filter_list.append(cls.UserID.contains(kwargs.get('keyword')))
        elif tag_name == '用户名':
            filter_list.append(cls.UserName.contains(kwargs.get('keyword')))

        try:
            result = db.session.query(cls.UserID,
                                      cls.UserName,
                                      cls.DepartmentID,
                                      DepartmentInfo.DepartmentName,
                                      cls.CreateTime).filter(*filter_list) \
                .join(DepartmentInfo, cls.DepartmentID == DepartmentInfo.DepartmentID)

            if not result.first():
                return {'code': RET.NODATA, 'message': "没有查询结果", 'data': []}

            return {'code': RET.OK, 'message': '查询数据成功', 'data': commons.query_to_dict(result.all())}

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}
